<template>
  <div class="login">
    <el-form
      :model="userForm"
      :rules="rules"
      status-icon
      ref="ruleForm"
      label-width="100px"
    >
      <el-form-item label="账号" prop="username">
        <el-input
          type="text"
          v-model="userForm.username"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="text"
          v-model="userForm.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm"
          :disabled="loading"
          :loading="loading"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import loginMixin from '@/mixin/loginMixin'
export default {
  data() {
    return {
      loading:false,
      userForm: {
        username: "",
        password: "",
        
      },
      
      rules: {
    username: [
      {type:'string',required: true, message: '请输入用户昵称', },
      //表单正则验证
      //{ pattern: /^a/, message: '必须a开头' }
      //自定义验证规则
      { validator: this.validateName }
    ],
    password: [
      {type:'string',required: true, message: '请输入密码', },
      {validator:this.validatePass}
    ],
  },
    };
  },
  mixins:[loginMixin],
  methods: {
    //自定义验证规则
   /*  validateName(rule, value, callback){
      if(/\s/i.test(value)){
        callback(new Error('空格不能当作用户名'))
      }else{
        callback( )
      }
    }, */
    submitForm(formName) {
      this.loading = true
      this.$refs["ruleForm"].validate(async (valid) => {
        
        if (valid) {
          let res =await this.$store.dispatch('user/loginAction',this.userForm)
          if(res){
            this.$router.replace('/admin')
          }else{
            this.$message({
            message: '用户名和密码要填写正确',
          type: 'error',
          duration: 1500,
          onClose:() => {
            this.loading = false
          }
          })
          }
        } else {
          this.$message({
            message: '用户名和密码要填写正确',
          type: 'error',
          duration: 1500,
          onClose:() => {
            this.loading = false
          }
          });
          return false;
        }
      });
    },
  },
  
};
</script>

<style lang="scss" scoped>
.login {
  width: 500px;
  margin: 150px auto;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 50px 10px;
}
</style>